<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>
        .box{width:300px;height:400px;border:solid 1px black;margin: 20px auto;}
        .msg{width:300px;height:300px;border-bottom:solid 1px black;overflow:auto}
        .msg div{max-width:200px;padding:6px;margin:6px;border-radius:6px;clear: both;}
        .msg div:nth-child(2n){background: #66f;float:left}
        .msg div:nth-child(2n-1){background: #6f6;float: right;}
    </style>
</head>
<body>
    <div class="box">
        <div class="msg"></div>
        <input type="text" id="txt">
        <input type="button" value="发送" id="send">
    </div>
</body>
<script>
    var msg = document.querySelector(".msg");
    var txt = document.getElementById("txt");
    var send = document.getElementById("send");

    

    send.onclick = function(){
        sendMsg();
    }


    // 敏感词库
    var arr = ["你好", "abc", "666", "$"];
    
    function sendMsg(){
        if(txt.value !== ""){
            var div = document.createElement("div");
            msg.appendChild(div);

            var str = txt.value;

            // 需要的正则
            // var reg1 = /((你好)|(abc)|(666)|(\$))+/g;

            // 拼接正则的主体字符
            var regStr = "";
            for(var i=0;i<arr.length;i++){
                // 拼接正则主体字符的过程中，如果遇到正则有含义的符号，需要单独处理
                regStr += "("+ fn(arr[i]) +")|";
            }
            // regStr："(你好)|(abc)|(666)|(\\$)|"
            
            // 根据拼接好的正则主体字符创建正则
            var reg = new RegExp("(" + regStr.slice(0,-1) + ")+", "g");
            // reg：/((你好)|(abc)|(666)|(\$))+/g

            // 根据正则替换敏感词
            str = str.replace(reg, "*");

            div.innerHTML = str;
            txt.value = "";
            msg.scrollTop = msg.scrollHeight;
        }
    }

    // 专为构造函数创建正则时，遇到有含义的正则符号时 的转义处理
    function fn(s){
        switch(s){
            case "+":
                return "\\" + s;
            case "*":
                return "\\" + s;
            case ".":
                return "\\" + s;
            case "$":
                return "\\" + s;
            case "^":
                return "\\" + s;
            // ......
            default:
                return s;
        }
    }


</script>
</html>